package com.hequ.merchant.banner.api;

import android.content.Context;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.hequ.merchant.banner.ApplicationHelper;
import com.hequ.merchant.banner.entity.Module;
import com.hequ.merchant.banner.util.Toasts;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 柯尊诚 on 2015/10/29.
 * kzc
 */
public class ModuleDataListLoader {

    private static ModuleDataListLoader instance;

    public static ModuleDataListLoader getInstance(Context context) {

        if(instance == null) {
            instance = new ModuleDataListLoader(context);
        }

        return instance;
    }

    private final RequestQueue requestQueue;
    private Context context;


    private ModuleDataListLoader(Context context) {
        this.context = context;
        requestQueue = Volley.newRequestQueue(context);
        requestQueue.start();
    }

    public void getList() {
        requestQueue.add(new ModuleListRequest(listener));
    }

    private OnRequestListener<List<Module>> listener = new SimpleRequestListener<List<Module>>() {
        @Override
        public void onSuccess(List<Module> data) {
            ModuleDataListLoader.this.onNetSuccess(data);
        }

        @Override
        public void onFailed() {
            ModuleDataListLoader.this.onNetFailed();
        }
    };

    public void onNetSuccess(List<Module> data) {
        Toasts.makeText("请求模块成功，共" + data.size() + "!");
        if (data != null && !data.isEmpty()) {
            //moduless.clear();
            //moduless.addAll(data);

            ApplicationHelper.getModules().clear();
            ApplicationHelper.getModules().addAll(data);

//            adapter.notifyDataSetChanged();

            for(OnDataRefreshListener listener : listeners) {
                listener.onRefresh();
            }

        }
    }

    public void onNetFailed() {
        Toasts.makeText("请求模块失败！");
    }

    private List<OnDataRefreshListener> listeners = new ArrayList<>();

    public void registerRefreshListener(OnDataRefreshListener listener) {
        if (listener != null && !listeners.contains(listener)) {
            listeners.add(listener);
        }
    }

    public void unregisterRefreshListener(OnDataRefreshListener listener) {
        if (listener != null) {
            listeners.remove(listener);
        }
    }

    public interface OnDataRefreshListener {
        void onRefresh();
    }

}
